package com.hmall.item.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/list")
    public PageDTO<Item> page(Integer page, Integer size) {

        Page<Item> page1 = itemService.page(new Page<>(page, size));
        log.info("蛤蛤,{},{}", page1.getTotal(), page1.getRecords());
        PageDTO pageDTO = new PageDTO(page1.getTotal(), page1.getRecords());
        return pageDTO;
    }

    @GetMapping("/{id}")
    public Item selectById(@PathVariable Long id) {
        Item byId = itemService.getById(id);
        return byId;
    }

    @PostMapping
    public void add(@RequestBody Item item) {

        itemService.save(item);
    }

    /**
     * MQ
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void status(@PathVariable Long id, @PathVariable Integer status) {
        Item byId = itemService.getById(id);
        byId.setStatus(status);
        itemService.updateById(byId);


        String queueName = "itenQueue";
        String jsonString = JSON.toJSONString(byId);
        rabbitTemplate.convertAndSend(queueName,jsonString);




    }


    @PutMapping
    public void updateall(@RequestBody Item item) {
        itemService.updateById(item);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        log.info("id:{}", id);
        itemService.removeById(id);
    }

}
